package solutions.ferpa.ztest.intf;

import br.com.telescope.adsrt.dom.DomFlag;
import br.com.telescope.adsrt.dom.DomId;
import br.com.telescope.adsrt.dom.DomInteger;
import br.com.telescope.adsrt.dom.DomText;
import br.com.telescope.adsrt.dom.DomTextHtml;
import br.com.telescope.adsrt.dom.DomTextLong;
import br.com.telescope.adsrt.dom.DomUpper;
import br.com.telescope.adsrt.lib.*;
import br.com.telescope.t2.ModuleNavigator;
import br.com.telescope.t2.ServiceModel;
import br.com.telescope.t2.exception.ApplicationRuntimeException;
import br.com.telescope.t2.feature.AbstractFeature;
import br.com.telescope.t2.feature.CustomActionFeature;
import br.com.telescope.t2.feature.DeleteFeature;
import br.com.telescope.t2.feature.InsertFeature;
import br.com.telescope.t2.feature.ListFeature;
import br.com.telescope.t2.feature.QueryFeature;
import br.com.telescope.t2.feature.UpdateFeature;
import br.com.telescope.util.JdbcUtil;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import solutions.ferpa.ztest.ent.*;
import solutions.ferpa.ztest.intf.*;

/**
 * Cadastro de Menus.
 * <p>
 * Interface para manutenção dos menus do sistema.
 * <P>
 * 
 * <P>
 * Um menu é composto por uma lista de itens que permitem ao usuário 
 * navegar para diferentes iinterfaces do sistema.
 * <P>
 * Após informar os atributos básicos do menu, informe seu ítens.
 * <P>
 * 
 * <P>
 * Telescope origin: RTMENU.CAD_MENU
 * <P>
 * Base entity: RTMENU.MENUS
 * <P>
 * @author TELESCOPE - Build task T2 Web Interface Generator
 * <P>
 * @version 0.1
 */
public class CadMenu extends ServiceModel {
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    public static final String GLOBAL_NAME = "RTMENU.CAD_MENU";
    
    @Override
    public String globalName() {
        return GLOBAL_NAME;
    }
    
    {
        setTitle("Cadastro de Menus");
    }
    
    protected EntMenus base;
    protected EntMenus rec; // NEED_TJW1_COMPATIBILITY
    
    // Record items
    private DomId aId;
    private DomUpper aMenu;
    private DomText aTitulo;
    private DomTextLong aDescricao;
    private DomInteger aSequencia;
    private DomFlag aTopo;
    private DomTextHtml aUnSubMenu;
    
    // Query items
    private DomInteger qSequencia;
    private DomTextLong qDescricao;
    private DomUpper qMenu;
    private DomText qTitulo;
    private DomFlag qTopo;
    
    @Override
    public String getBaseSql() {
        return "select BASE.*"
                + " from MENUS BASE";
    }
    
    @Override
    public void initAttributes() {
        
        aId = new DomId();
        aId.context(ctx).name("ID").label("Id");
        
        aMenu = new DomUpper();
        aMenu.context(ctx).name("MENU").label("Menu");
        
        aTitulo = new DomText();
        aTitulo.context(ctx).name("TITULO").label("Título");
        
        aDescricao = new DomTextLong();
        aDescricao.context(ctx).name("DESCRICAO").label("Descrição");
        
        aSequencia = new DomInteger();
        aSequencia.context(ctx).name("SEQUENCIA").label("Sequência");
        aSequencia.setDefaultValue("50");
        
        aTopo = new DomFlag();
        aTopo.context(ctx).name("TOPO").label("Topo");
        aTopo.setDefaultValue("N");
        
        aUnSubMenu = new DomTextHtml();
        aUnSubMenu.context(ctx).name("UN_SUB_MENU").label("Sub-menu").unbound(true);
        
        
        qSequencia = new DomInteger();
        qSequencia.context(ctx).name("SEQUENCIA").label("Sequência");
        
        qDescricao = new DomTextLong();
        qDescricao.context(ctx).name("DESCRICAO").label("Descrição");
        
        qMenu = new DomUpper();
        qMenu.context(ctx).name("MENU").label("Menu");
        
        qTitulo = new DomText();
        qTitulo.context(ctx).name("TITULO").label("Título");
        
        qTopo = new DomFlag();
        qTopo.context(ctx).name("TOPO").label("Topo");
    }
    
    @Override
    public String getQueryPkColumn() {
        return "BASE.ID";
    }
    
    @Override
    public void setId(String value) {
        this.aId.setValue(value);
    }
    
    @Override
    public EntMenus getRecord() {
        if (base == null) {
            base = new EntMenus(ctx);
            rec = base;
        }
        return this.base;
    }
    
    @Override
    public String getContextName() {
        return aMenu.toText();
    }
    
    @Override
    public String getDefaultOrderBy() {
        return "MENU, TITULO, DESCRICAO, SEQUENCIA";
    }
    
    @Override
    public ModuleNavigator getDefaultModuleNavigator() {
        return new ModMenu();
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="QUERY">
    public class FQuery extends QueryFeature {
        
        @Override
        public void initForm() {
            qMenu.setDefaultValue("|s");
            addField(qMenu, "opt");
            addField(qTitulo, "opt");
            addField(qDescricao, "opt");
            addField(qSequencia, "opt");
            addField(qTopo, "opt");
        }
        
        @Override
        public void onAction() {
            addSubmit(getFeature("REFRESH_MENUS")).label("Refresh menus").shortCutKey("F6");
        }
        
        {
            setFeatureName("QUERY");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="LIST">
    public class FList extends ListFeature {
        
        @Override
        public void initForm() {
            addField(aMenu, "view");
            addField(aTitulo, "view");
            addField(aDescricao, "view");
            addField(aSequencia, "view");
            addField(aTopo, "view");
        }
        
        @Override
        public void onAction() {
            addSubmit(getFeature("REFRESH_MENUS")).label("Refresh menus").shortCutKey("F6");
        }
        
        {
            setFeatureName("LIST");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="INSERT">
    public class FInsert extends InsertFeature {
        
        @Override
        public void initForm() {
            aMenu.setOptional(false);
            addField(aMenu, "rqd");
            aTitulo.setOptional(false);
            addField(aTitulo, "rqd");
            addField(aDescricao, "opt");
            addField(aSequencia, "opt");
            addField(aTopo, "opt");
        }
        
        {
            setFeatureName("INSERT");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="UPDATE">
    public class FUpdate extends UpdateFeature {
        
        @Override
        public void initForm() {
            aMenu.setOptional(false);
            addField(aMenu, "rqd");
            aTitulo.setOptional(false);
            addField(aTitulo, "rqd");
            addField(aDescricao, "opt");
            addField(aSequencia, "opt");
            addField(aTopo, "opt");
            aUnSubMenu.setEditable(false);
            addField(aUnSubMenu, "view");
        }
        
        @Override
        public void preDisplay() {
            try {
                montarListaSubMenus();
            } catch (AdsException ex) {
                throw new ApplicationRuntimeException(ex);
            }
        }
        
        @Override
        public void posDisplay() {
            {
                CadItemMenu external = new CadItemMenu();
                external.setRuntime(ctx.clone());
                external.init();
                AbstractFeature feature = external.getFeature("LIST");
                external.setParameterMenuId(aId.getValue());
                external.setDetail(true);
                feature.setTitle("Itens de menu");
                feature.run();
            }
        }
        
        @Override
        public void onAction() {
            addSubmit(getFeature("REFRESH_MENUS")).label("Refresh menus").shortCutKey("F6");
        }
        
        {
            setFeatureName("UPDATE");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="DELETE">
    public class FDelete extends DeleteFeature {
        
        @Override
        public void initForm() {
            addField(aMenu, "view");
        }
        
        {
            setFeatureName("DELETE");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="REFRESH_MENUS">
    public class FRefreshMenus extends CustomActionFeature {
        
        @Override
        public void initForm() {
        }
        
        @Override
        public void execute() {
            try {
                refreshMenus();
            } catch (AdsException ex) {
                throw new ApplicationRuntimeException(ex);
            }
        }
        
        {
            setFeatureName("REFRESH_MENUS");
            setTitle("Refresh menus");
            setShortCutKey("F6");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="initFeatures">
    
    @Override
    protected void initFeatures() {
        addFeature(new FQuery());
        addFeature(new FList());
        addFeature(new FInsert());
        addFeature(new FUpdate());
        addFeature(new FDelete());
        addFeature(new FRefreshMenus());
        super.initFeatures();
    }
    
    @Override
    public String getDefaultFeature() {
        return "QUERY";
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="Getters and Setters">
    
    @Override
    public Long getId() {
        return aId.getValue();
    }
    
    public void setId(Long value) {
        this.aId.setValue(value);
    }
    
    public String getMenu() {
        return aMenu.getValue();
    }
    
    public void setMenu(String value) {
        this.aMenu.setValue(value);
    }
    
    public String getTitulo() {
        return aTitulo.getValue();
    }
    
    public void setTitulo(String value) {
        this.aTitulo.setValue(value);
    }
    
    public String getDescricao() {
        return aDescricao.getValue();
    }
    
    public void setDescricao(String value) {
        this.aDescricao.setValue(value);
    }
    
    public Integer getSequencia() {
        return aSequencia.getValue();
    }
    
    public void setSequencia(Integer value) {
        this.aSequencia.setValue(value);
    }
    
    public String getTopo() {
        return aTopo.getValue();
    }
    
    public void setTopo(String value) {
        this.aTopo.setValue(value);
    }
    
    public String getUnSubMenu() {
        return aUnSubMenu.getValue();
    }
    
    public void setUnSubMenu(String value) {
        this.aUnSubMenu.setValue(value);
    }
    public String getQueryMenu() {
        return qMenu.getQueryValue();
    }
    
    public void setQueryMenu(String value) {
        this.qMenu.setQueryValue(value);
    }
    public String getQueryTitulo() {
        return qTitulo.getQueryValue();
    }
    
    public void setQueryTitulo(String value) {
        this.qTitulo.setQueryValue(value);
    }
    public String getQueryDescricao() {
        return qDescricao.getQueryValue();
    }
    
    public void setQueryDescricao(String value) {
        this.qDescricao.setQueryValue(value);
    }
    public String getQuerySequencia() {
        return qSequencia.getQueryValue();
    }
    
    public void setQuerySequencia(String value) {
        this.qSequencia.setQueryValue(value);
    }
    public String getQueryTopo() {
        return qTopo.getQueryValue();
    }
    
    public void setQueryTopo(String value) {
        this.qTopo.setQueryValue(value);
    }
    // </editor-fold>
    
    /**
     * Refresh menus.
     * <p>
     * Atualiza os menus da sessão do usuário corrente. Permite testar e 
     * visualizar as alterações realizadas.
     */
    public void refreshMenus() throws AdsException {
        // <user-code id="22538278" parentId="22538265" hashcode="-76f38620" length="23">
        refreshSessionMenu();
        
        // </user-code>
    }
    
    /**
     * Montar lista de sub-menus.
     */
    private void montarListaSubMenus() throws AdsException {
        // <user-code id="7472044" parentId="7472043" hashcode="5bce0b6b" length="938">
        // import java.sql.PreparedStatement;
        // import java.sql.ResultSet;
        // import br.com.telescope.util.JdbcUtil;
        
        aUnSubMenu.nullify();        
        if (getBdProductName().contains("POSTGRES")) {
            PreparedStatement ps = null;
            ResultSet rs = null;
        
            try {
                ps = ctx.getConnection().prepareStatement(
                        "select array_to_string(ARRAY("
                        + " select"
                        + " '<a href=\"CadMenu?Z_ACTION=UPDATE&A_ID='||m.id||'\">'||m.menu||'</a>'"
                        + " from itens_menus im "
                        + " inner join menus m on m.id = im.menu_id"
                        + " where sub_menu_id = ?), ',')"
                        );
                ps.setLong(1, aId.getValue());
                rs = ps.executeQuery();
                if (rs.next()) {
                    aUnSubMenu.setValue(rs.getString(1));
                }
            } catch (Exception ignore) {
                // ignore
            } finally {
                JdbcUtil.close(ps, rs);
            }
        }
        // </user-code>
    }
    
    /**
     * z Code.
     */
    // <user-code id="7473510" parentId="7473507" hashcode="-3c1f5918" length="401">
    String bdProductName = null;
    
    // Preenche a variável bdProductName
    private String getBdProductName() {
        if (bdProductName == null) {
            try {
                bdProductName = ctx.getConnection()
                        .getMetaData().getDatabaseProductName().toUpperCase();
            } catch (Exception ex) {
                bdProductName = null;
            }
        }
        return bdProductName;
    }   
    
    // </user-code>
}
